﻿using System.Collections.Generic;
using System.Linq.Expressions;

namespace Sita.Data.Core.Specification
{
    public class ParameterRebinder : ExpressionVisitor
    {
        private readonly Dictionary<ParameterExpression, ParameterExpression> m_Map;

        public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
        {
            this.m_Map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
        }
        public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
        {
            return new ParameterRebinder(map).Visit(exp);
        }
        protected override Expression VisitParameter(ParameterExpression p)
        {
            ParameterExpression Replacement;

            if (m_Map.TryGetValue(p, out Replacement))
            {
                p = Replacement;
            }

            return base.VisitParameter(p);
        }
    }
}
